<template>
	<view class="wrap">
		<!-- 接收子组件传递的参数close -->
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cuBar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描机台" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
			
		</view>
		<view class="cu-bar search" style="padding: 10px" ref="cuBar" v-if="lineCode">
			<u-form style="width: 100%;">
				<u-form-item label="机台" prop="id" label-width="180" style="font-weight: 800;">
					<view>{{ lineCode}}</view>
				</u-form-item>
			</u-form>
			
		</view>
		
		<view v-show="currentRW ">
			<scroll-view
			  scroll-y="true"
			  :style="{ height: computedScrollViewHeight }"
			  
			>
			<!-- style="margin: 20px 0" -->
				<view class="margin-sm">
					<u-section
					  title="当前机台正在加工任务"					  
					  :right="false"
					  line-color="blue"
					  font-size="30"
					  v-if="list.length>0"
					></u-section>
					<view class="wrap" v-if="list.length>0">
						<u-form class="form" ref="uForm" label-position="left" :model="model" :rules="rules" v-for="(item,index) in list">
							<u-form-item label="" prop="id" label-width="180">
								<template>
									<view class="flex title">
										<view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px	;">
											{{ index + 1 }}
										</view>
										<!-- <view>订单号</view> -->
									</view>
									<view class="flex align-center justify-end flex-sub">
										<!-- <view>{{ item.scOrder ? item.scOrder.code : ''}}{{item.scOrder ?  item.scOrder.sortNum ? '#' + item.scOrder.sortNum : '' : ''}}</view> -->
										<view class="flex align-center">			
											<dictLabel
											v-if="!item.isDelFlag"
											:value="item.taskStatus ? item.taskStatus : ''"
											dict-type="mes_task_status"
											:dict-list="dictList"
											:fontSize="'30rpx'"
											></dictLabel>
											<text class="cuIcon-deletefill padding text-sl text-red" @tap="DelItem(item)" v-if="!!item.isDelFlag"></text>
										</view>
										
									</view>
								</template>
							</u-form-item>
							<u-form-item label="" prop="scOrder" label-width="180">
								<template>
									<view class="flex title"><view>订单号</view></view>
									<view class="flex align-center justify-between flex-sub">
										<view>{{ item.scOrder ? item.scOrder.code : ''}}{{item.scOrder ?  item.scOrder.sortNum ? '#' + item.scOrder.sortNum : '' : ''}}</view>
									</view>
								</template>
							</u-form-item>
							
							
							<u-form-item label="报工数" prop="bgQty" label-width="180" style="color: red;font-weight: 800;" :required="true">
								<u-input placeholder="请输入" v-model="item.bgQty" type="text" maxlength="64" :custom-style="customStyle"  @input="onInputFirstBgQty($event, item, index)" :focus="false"></u-input>
							</u-form-item>
							<u-form-item label="操作工" prop="operator" label-width="180" style="color: red;font-weight: 800;" :required="true">
								<u-input placeholder="请扫码" v-model="item.operator" type="text" maxlength="64" :custom-style="customStyle" disabled></u-input>
							</u-form-item>
							<u-form-item label="剩余报工数" prop="syBgQty" label-width="180" style="color: red;font-weight: 800;" >
								{{ item.syBgQty || '0' }} 
							</u-form-item>
							<u-form-item label="工序名称" prop="id" label-width="180">
								<view>{{ item.basOper.name}}</view>
							</u-form-item>
							<u-form-item label="存货编码" prop="id" label-width="180">
								<view>{{ item.basInv ? item.basInv.cinvcode || '' : ''}}</view>
							</u-form-item>
							<u-form-item label="存货名称" prop="id" label-width="180">
								<view>{{ item.basInv ? item.basInv.cinvname || '' : ''}}</view>
							</u-form-item>
							<u-form-item label="规格型号" prop="id" label-width="180">
								<view>{{ item.basInv.cinvstd || ''}}</view>
							</u-form-item>
							<u-form-item label="任务数量" prop="iqty" label-width="180">
								{{ item.iqty }}
							</u-form-item>
							
							
							<u-form-item label="计件单价" prop="id" label-width="180">
								<view>{{ item.iprice }}</view>
							</u-form-item>
							<!-- <u-form-item label="报工人" prop="id" label-width="180">
								<view>{{ item.createByName }}</view>
							</u-form-item> -->


						</u-form>
					</view>
					<view v-if="list.length==0">
						<u-empty :style="{height: emptyViewHeight+'px'}">
							<template #bottom>
								<view>当前机台暂无执行任务</view>
							</template>
						</u-empty>
					</view>
				</view>
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group" >
				<!-- round -->
				<button class="cu-btn  bg-confirm lg margin-left " @click="confirm" v-if="list.length>0">报工</button>	
					<button class="cu-btn  lines-red lg " @click="selectSJ" v-if="lineCode">选择报工任务</button>
					<button class="cu-btn  lines-red lg " @click="selectSJUser">(当前人)任务</button>
			</view>
		</view>
		<view class="btn-group cu-bar foot padding" ref="btn-group" v-show="!currentRW ">
			<!-- round -->
			<button class="cu-btn  lines-red lg " @click="selectSJUser">(当前人)任务</button>
		</view>
		<u-empty v-if="!currentRW" :style="{height: emptyViewHeight+'px'}"></u-empty>
		<custom-modal ref="customModal" v-if="showModal" :initial-message="modalMessage" @update:close="onModalClose" ></custom-modal>
	</view>
</template>

<script>
	import CustomModal from "@/pages/mes/components/CustomModal.vue";
	import dictLabel from "@/pages/mes/components/dictLabel.vue";
	export default {
		components: {
			CustomModal,
			dictLabel
		},
		data() {
			return {
				focus:true,
				barCode:'',
				model: {
					iqty:10,
					operator:''
				},
				rules: {
					operator: [
						{
							required: true,
							message: '请扫码操作工',
							trigger: ['change','blur'],
						}
					]
				},
				customStyle:{
					color:'red'
				},
				showModal: false,
				scrollViewHeight: 0,
				currentRW:false,
				emptyViewHeight:0,
				barCodeCode:'',
				list:[],
				operatorNames: {},
				modid:'',
				lineCode:'',
				firstItemIndex: 0, // 假设第一个项目是列表的第一个元素
				dictList:[],
			}
		},
		onShow() {
			// 在onShow中监听事件
			// uni.$once('selectedItems', (selectedItems) => {
			// 	this.focus = false
			// 	setTimeout(() => {
			// 		this.focus = true
			// 	}, 500)
			// 	// 去重
			// 	const uniqueSelectedItems = Array.from(new Set(selectedItems.map(item => item.id)));
			// 	// 从this.list中过滤出不在uniqueSelectedItems中的项
			// 	const filteredList = this.list.filter(item => !uniqueSelectedItems.includes(item.id));
			// 	// 合并并去重
			// 	this.list = [...filteredList, ...selectedItems].filter(
			// 		(item, index, self) => self.findIndex(i => i.id === item.id) === index
			// 	);
			// 	console.log(this.list, 'merged and deduplicated list');
			// });
			console.log('selectedItems')
			uni.$once('selectedItems', (selectedItems) => {
				if (!Array.isArray(selectedItems)) {
					console.error('selectedItems is not an array');
					return;
				}
				this.focus = false
				setTimeout(() => {
					this.focus = true
				}, 500)
				// 去重
				const uniqueSelectedItems = Array.from(new Set(selectedItems.map(item => item.id)));
				// // 从this.list中过滤出不在uniqueSelectedItems中的项
				// const filteredList = this.list.filter(item => !uniqueSelectedItems.includes(item.id));
				// // 合并并去重
				// this.list = [...filteredList, ...selectedItems].filter(
				// 	(item, index, self) => self.findIndex(i => i.id === item.id) === index
				// );
				// 直接替换list
				this.list = selectedItems;
				this.currentRW = true;
				console.log(this.list, 'merged and deduplicated list');
			});
			this.getDictList()
		},
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		onUnload(){
			uni.$off('selectedItems');
		},
		methods:{
			getDictList() {
				this.$u.api
					.dictListData({ dictType: "mes_task_status" })
					.then((res) => {
					this.dictList = res;
				});		
			},
			onInputFirstBgQty(value, item, index) {
				// 确保只有第一个项目的输入才触发更新
				if (index === this.firstItemIndex) {
					this.list.forEach((itm) => {
						itm.bgQty = value; // 同步更新所有项目的bgQty
					});
				}
			},
			DelItem(item) {
				this.showCustomModal("确定删除吗？").then((res) => {
					if(res){
						const index = this.list.findIndex((element) => element.id === item.id); // 假设每个item有一个唯一的id属性
						if (index !== -1) {
							// 从数组中移除找到的项
							this.list.splice(index, 1);
						}
					}
				})
			},
			async calculateScrollViewHeight() {
			  try {
			// 等待头部高度计算完成
				await this.$nextTick(); // 确保DOM更新完成
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 0 : 0;
				  const cuBarOffsetHeight = this.$refs['cuBar'] ? this.$refs['cuBar'].$el ? this.$refs['cuBar'].$el.offsetHeight : 109 : 0 ;
				  
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( btnOffsetHeight + cuBarOffsetHeight + 80 );
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
			// 等待头部高度计算完成
			      
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cuBar'] ? this.$refs['cuBar'].$el ? this.$refs['cuBar'].$el.offsetHeight : 109 : 0;
				  
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight ;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async confirmSearch(){		
				this.focus = false
				console.log(this.barCode,'barCode')
				this.commonSearch(this.barCode)			
				// await this.$nextTick();
				setTimeout(() => {
					this.focus = true;
				}, 500);
				// this.$nextTick(() => {
				// // 在这里安全地使用 this.$refs.uSearch.$el.querySelector(...)
				// console.log(this.$refs.uSearch,'uSearch')
				// 	if (this.$refs.uSearch && this.$refs.uSearch.$el) {
				// 		const inputElement = this.$refs.uSearch.$el.querySelector('input');
				// 		console.log(inputElement,'inputElement',this.$refs.uSearch.$el)
				// 		if (inputElement) {
				// 			inputElement.focus();
				// 		}
				// 	} else {
				// 		console.warn('uSearch ref or its element is not available yet.');
				// 	}
				// });

			},


			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				console.log(this.barCode.indexOf(JT),'JT',this.barCode,JT,this.barCode.indexOf(GP))
				if (barCode.indexOf(JT) == -1 && barCode.indexOf(GP) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的机台或工牌",'error');
					setTimeout(() => {
						this.barCode = ''
						this.focus = true;
					}, 500);
					return;
				}else if(barCode.indexOf(JT) == 0){
					this.barCodeCode = barCode
					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.BAR_FUN_TYPE_BG,
						barJT:barCode
					})
					if(res.result == "true"){
						await this.$nextTick();
						this.barCode = '';
						this.lineCode = res.basLine.code
						const resResult = await this.$u.api.kst.getBgTaskByLineCode({
							lineCode:this.lineCode
						})
						if(resResult.result == "true"){
							this.currentRW = true;
							if(resResult.data.length == 1){
								this.list = resResult.data
								this.list.forEach(item=>{
									item.operator = ''
								})
								this.modid = this.list.length > 0 ? this.list[0]['modid'] : ''
								setTimeout(() => {
									this.focus = true;
									this.barCode = ''; // Reset only if needed after successful operation
								}, 500);
								// await this.$nextTick();
								this.focus = true;
								console.log(this.$refs.uSearch,'uSearch')
								this.$refs.uSearch.focused = true;
								this.$refs.uSearch.getFocus();
							}else if(resResult.data.length > 1){
								this.selectSJ()
							}else if(resResult.data.length == 0) {
								this.list.forEach(item=>{
									item.operator = ''
									item.syBgQty = '0'
								})
								this.focus = true;
								console.log(this.$refs.uSearch,'uSearch')
								this.$refs.uSearch.focused = true;
								this.$refs.uSearch.getFocus();
							}

						}else{
							this.$refs.jsError.showError('', res.message, 'error');
							setTimeout(() => {
								this.focus = true;
							}, 500);
						}
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.focus = true;
							this.barCode = ''
						}, 500);
					}
				} else if(barCode.indexOf(GP) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.GP,
						barGP:barCode
					})
					if(res.result == "true"){

						let operatorName = res.operator.name;
						// 累加操作员名称或设置初始值
						if (this.operatorNames[barCode]) {
							operatorName = `${this.operatorNames[barCode]},${operatorName}`;
						}
						this.operatorNames[barCode] = operatorName;
						// this.operatorNames 去重
						this.operatorNames = [...new Set(Object.values(this.operatorNames))]
						
						const operatorNamesStr = Object.values(this.operatorNames).join(',');
						await this.$nextTick();
						this.barCode = '';
						this.list.forEach((item) => {
							item.operator = operatorNamesStr
						});	
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
						this.$forceUpdate()	
					}else{
						this.$refs.jsError.showError('', res.message, 'error');
						setTimeout(() => {
							this.barCode = '';
							this.focus = true;
						}, 500);
					}
				}
				
			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;						
						await _that.commonSearch(res.result)
					},
				});
			},




			confirm(){
				// 获取list的id,字符串逗号分隔
				let taskList = [];
				// 遍历list ,把taskId，iqty，operator
				this.list.forEach((item) => {
					taskList.push({
						taskId:item.id,
						iqty:item.bgQty,
						operator:item.operator
					})
				});

				const validationErrors = [];
				// 检测taskList的必填项
				taskList.forEach((item) => {
					if(!item.operator || !item.iqty){
						validationErrors.push(`任务${item.taskId}：工号和报工数量必填`)
					}
				});
				if (validationErrors.length > 0) {
					this.$refs.jsError.showError('', validationErrors.join('\n'), 'error');
					return;
				}

				this.$u.api.kst.batchTaskRep(taskList).then( async (res)=>{
					console.log(res.result,res.result=="true")
					if(res.result=="true"){
						this.$u.toast(res.message);
						// this.list = []
						this.focus = false;
						// 清空操作工
						this.operatorNames = {};
						if(!!this.barCodeCode){
							this.commonSearch(this.barCodeCode)
							this.$forceUpdate()
						}else{
							// 
							const id = this.list[0]['id']
							const resResult = await this.$u.api.kst.getBgTaskByUserCode({
								id:id
							})
							console.log(resResult,'resResult.result')
							if(resResult.result == "true"){
								if(resResult.data.length == 1){
									this.list = resResult.data
									this.list.forEach(item=>{
										item.operator = this.vuex_user.userName
									})
									this.modid = this.list.length > 0 ? this.list[0]['modid'] : ''
									setTimeout(() => {
										this.focus = true;
										this.barCode = ''; // Reset only if needed after successful operation
									}, 500);
									// await this.$nextTick();
									this.focus = true;
									console.log(this.$refs.uSearch,'uSearch')
									this.$refs.uSearch.focused = true;
									this.$refs.uSearch.getFocus();
								}else if(resResult.data.length > 1){
									this.selectSJUser()
								}else if(resResult.data.length == 0) {
									this.list.forEach(item=>{
										item.operator = ''
										item.syBgQty = '0'
									})
									this.focus = true;
									this.$refs.uSearch.focused = true;
									this.$refs.uSearch.getFocus();
								}

							}else{
								console.log()
								this.$refs.jsError.showError('', resResult.message, 'error');
								setTimeout(() => {
									this.focus = true;
								}, 500);
							}
						}
						
					}else{
						// this.$u.toast(res.message);
						this.focus = false;
						console.log('focus',this.focus)
						this.$refs.jsError.showError('',res.message,'error');
						
					}
				})

			},
			
			
			selectSJ(){
				uni.navigateTo({
					url: "/pages/mes/baogong/bSelect?modid=" + this.modid + '&lineCode=' + this.lineCode
				});
			},
			selectSJUser(){
				uni.navigateTo({
					url: "/pages/mes/baogong/bSelect"
				});
			},
			async showCustomModal(message) {
			  this.modalMessage = message;
			  this.showModal = true;
			  // 模拟同步等待用户操作
			  return new Promise((resolve) => {
			    this.onModalClose = (result) => {
			      this.modalResult = result;
			      this.showModal = false;
			      resolve(this.modalResult);
			    };
			  });
			},
			onModalClose(result) {
			  this.$emit("update:close", result);
			},
			onErrorClose(result) {
			//   this.$emit("update:errorcClose", result);
			//   获取focus 焦点
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
			 
			},
		}
	}	
</script>

<style scoped>
	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
	.title{
		width: 180rpx;
	}
	.text-sl{
		font-size: 60rpx;
	}
</style>